home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4332 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: gsusgi1.gsu.edu!not-for-mail
  2. From: matmrlx@gsusgi1.gsu.edu (Michael R. Lauer)
  3. Newsgroups: comp.lang.c
  4. Subject: free space malloced to auto vars??
  5. Date: 1 Feb 1996 08:29:58 -0500
  6. Organization: Georgia State University
  7. Message-ID: <4eqf8m$smv@gsusgi1.gsu.edu>
  8. NNTP-Posting-Host: gsusgi1.gsu.edu
  9. Summary: Do I free space malloced to auto vars on leaving scope?
  10. Keywords: malloc
  11. X-Newsreader: NN version 6.5.0 #3 (NOV)
  12.  
  13. The general question is: if you malloc space for a pointer with automatic
  14. storage, should/must you free that space before leaving that scope?
  15.  
  16. This seems obvious but it is giving me trouble. In this code:
  17.  
  18. {
  19.     struct dirent *dp;
  20.     if ((dp = readdir() != NULL)
  21.     {
  22.     }
  23.     if (dp)                /* this seems to cause a segmentation fault */
  24.         free(dp);        /* when the enclosing function returns */
  25. }
  26.  
  27. So readdir returns a pointer to the dirent structure--it is mallocing the
  28. space. When I leave this scope I AM done with dp and the struct. 
  29. Don't I have to free(dp)? The "if(dp) free(dp)" at the end of the scope caused 
  30. a segmentation fault when I returned from the enclosing function. It 
  31. apparently works fine without the free(), but I am worried about memory 
  32. leakage.
  33.  
  34.